#include "threadPool.h"
#define MAX_EVENTS 2
#define BUFFER_SIZE 4096
int exitPipe[2];
void sigFunc(int signum)
{
    printf("signum = %d\n", signum);
    write(exitPipe[1], "1", 1);
    printf("parent got signal\n");
}

int main(int argc, char *argv[])
{
    // sudo ./server 192.168.253.128 1234 3
    //~/linux/ftpplus/ThreadPool
    ARGS_CHECK(argc, 4); // 检查参数个数 ip 端口 worker进程的数量
    // 创建父子进程
    pipe(exitPipe);
    if (fork() != 0)
    { // 父进程的代码
        close(exitPipe[0]);
        signal(SIGUSR1, sigFunc);
        wait(NULL);
        exit(0);
    }
    close(exitPipe[1]);
    // 解析命令行参数
    int workerNum = atoi(argv[3]); // 获取子线程的数量
    // 初始化相关的数据结构
    threadPool_t threadPool;
    threadPoolInit(&threadPool, workerNum);
    // 创建若干个子线程
    makeWorker(&threadPool);
    // 主线程准备建立tcp连接
    int sockfd;
    usraddr usr;
    // 存储盐值
    //  char password[100]="$1$26gzAH48$98XSesgL.mGaVx111aEGL";
    char salt[100] = "";
    int satLen = 0;
    struct spwd *sp;
    tcpInit(argv[1], argv[2], &sockfd);

    // 启动epoll 监听sockfd
    int epfd = epollCtor();
    epollAdd(epfd, sockfd);
    epollAdd(epfd, exitPipe[0]);
    struct epoll_event readyset[2];
    while (1)
    {
        int readynum = epoll_wait(epfd, readyset, 2, -1);
        for (int i = 0; i < readynum; ++i)
        {
            if (readyset[i].data.fd == sockfd)
            {
                // 把这个netfd放入任务队列当中
                int netfd = accept(sockfd, NULL, NULL);
                log_INFO("Client connected.");
                // 接受用户名
                log_INFO("password pass.");

                pthread_mutex_lock(&threadPool.taskQueue.mutex);
                taskEnQueue(&threadPool.taskQueue, netfd);
                log_INFO("main sent a new task!");
                pthread_cond_signal(&threadPool.taskQueue.cond);
                pthread_mutex_unlock(&threadPool.taskQueue.mutex);
            }
            else if (readyset[i].data.fd == exitPipe[0])
            {
                printf("threadPool exit!\n");
                pthread_mutex_lock(&threadPool.taskQueue.mutex);
                threadPool.isexit = 1; // 修改退出标志位
                pthread_cond_broadcast(&threadPool.taskQueue.cond);
                pthread_mutex_unlock(&threadPool.taskQueue.mutex);
                for (int j = 0; j < workerNum; ++j)
                {
                    pthread_join(threadPool.tidArr[j], NULL);
                }
                puts("done");
                exit(0);
            }
        }
    }
}